package com.tjetc;

import com.tjetc.utils.JdbcUtil;
import org.junit.jupiter.api.Test;

import java.sql.Connection;
import java.sql.PreparedStatement;

/**
 * @ author: gaoyongxiang
 * @ date: 2025/8/15
 * @ version: v1.0
 */
public class _6Batch {
    /*
        批处理：
     */
    @Test
    public void testBatch1() throws Exception {
        Connection connection = JdbcUtil.getConnection();
        String sql = "insert into bank (name, money) values ('zhangsan', 1000)";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        // 执行前统计一下时间
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 50000; i++) {
            preparedStatement.executeUpdate();
        }
        long endTime = System.currentTimeMillis();
        System.out.println(endTime - startTime);
        JdbcUtil.close(null, preparedStatement, connection);
    }

    @Test
    public void testBatch2() throws Exception {
        Connection connection = JdbcUtil.getConnection();
        String sql = "insert into bank (name, money) values ('zhangsan', 1000)";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        // 执行前统计一下时间
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 50000; i++) {
            // 批处理减少我们发送sql的网络开销，并且通过preparedStatement减少了编译次数，所以效率大大提高了
            // 底层使用了ArrayList存储 扩容为1.5倍， 默认是10空间
            preparedStatement.addBatch();
            if ((i + 1) % 10000 == 0) {
                preparedStatement.executeBatch();
                preparedStatement.clearBatch();
            }
        }
        long endTime = System.currentTimeMillis();
        System.out.println(endTime - startTime);
        JdbcUtil.close(null, preparedStatement, connection);
    }



}